import {
  CANVAS_WIDTH,
  CANVAS_HEIGHT,
  BULLET_COOLDOWN,
  ENEMY_SPAWN_INTERVAL,
  POWERUP_DROP_CHANCE,
} from './utils/constants.js'
import { checkCollision, playSound } from './utils/helpers.js'
import Player from './entities/Player.js'
import Bullet from './entities/Bullet.js'
import EnemyFactory from './entities/EnemyFactory.js'
import Explosion from './entities/Explosion.js'
import PowerUpFactory from './entities/PowerUpFactory.js'
import BossFactory from './entities/BossFactory.js'

// 游戏类
export default class Game {
  constructor() {
    // 游戏状态
    this.running = false
    this.score = 0
    this.lives = 3
    this.lastBulletTime = 0
    this.lastEnemySpawnTime = 0
    this.enemySlowFactor = 1 // 敌机减速因子，默认为1（正常速度）
    this.lastBossSpawnScore = 0 // 上一次生成Boss的分数
    this.bossActive = false // 是否有Boss正在活动

    // 游戏对象
    this.player = new Player()
    this.bullets = []
    this.enemies = []
    this.explosions = []
    this.powerUps = [] // 道具数组
    this.statusEffects = [] // 状态效果数组
    this.pickupEffects = [] // 道具拾取特效
    this.specialEffects = [] // 特殊视觉效果
    this.boss = null // 当前Boss
    this.bossBullets = [] // Boss发射的子弹

    // 获取DOM元素
    this.canvas = document.getElementById('gameCanvas')
    this.ctx = this.canvas.getContext('2d')
    this.startScreen = document.getElementById('startScreen')
    this.gameOverScreen = document.getElementById('gameOverScreen')
    this.startButton = document.getElementById('startButton')
    this.restartButton = document.getElementById('restartButton')
    this.scoreElement = document.getElementById('score')
    this.livesElement = document.getElementById('lives')
    this.finalScoreElement = document.getElementById('finalScore')
    this.statusEffectsElement = document.getElementById('statusEffects')
    this.messageElement = document.getElementById('message')

    // 设置Canvas尺寸
    this.canvas.width = CANVAS_WIDTH
    this.canvas.height = CANVAS_HEIGHT

    // 绑定事件处理器
    this.bindEvents()
  }

  // 初始化游戏
  init() {
    this.running = true
    this.score = 0
    this.lives = 3
    this.bullets = []
    this.enemies = []
    this.explosions = []
    this.powerUps = []
    this.statusEffects = []
    this.enemySlowFactor = 1
    this.pickupEffects = []
    this.specialEffects = []
    this.boss = null
    this.bossBullets = []

    this.player.reset()

    this.updateUI()
    this.startScreen.style.display = 'none'
    this.gameOverScreen.style.display = 'none'

    // 开始游戏循环
    requestAnimationFrame(this.gameLoop.bind(this))
  }

  // 游戏循环
  gameLoop(timestamp) {
    if (!this.running) return

    this.update(timestamp)
    this.render()

    requestAnimationFrame(this.gameLoop.bind(this))
  }

  // 更新游戏状态
  update(timestamp) {
    // 更新玩家
    this.player.update()

    // 发射子弹
    if (
      this.player.isShooting &&
      timestamp - this.lastBulletTime > BULLET_COOLDOWN
    ) {
      // 根据武器等级发射不同数量和类型的子弹
      this.fireBullets()
      this.lastBulletTime = timestamp

      // 播放射击音效
      playSound('shoot')
    }

    // 更新子弹位置
    for (let i = this.bullets.length - 1; i >= 0; i--) {
      this.bullets[i].update()

      // 移除超出屏幕的子弹
      if (this.bullets[i].isOutOfScreen()) {
        this.bullets.splice(i, 1)
      }
    }

    // 更新敌机
    this.updateEnemies(timestamp)

    // 更新Boss
    this.updateBoss(timestamp)

    // 更新爆炸效果
    this.updateExplosions()

    // 更新道具
    this.updatePowerUps()

    // 更新状态效果
    this.updateStatusEffects()

    // 更新拾取特效
    this.updatePickupEffects()

    // 更新特殊视觉效果
    this.updateSpecialEffects()

    // 检测碰撞
    this.checkCollisions()

    // 生成敌机
    if (
      !this.bossActive &&
      timestamp - this.lastEnemySpawnTime > ENEMY_SPAWN_INTERVAL
    ) {
      this.lastEnemySpawnTime = timestamp
      this.spawnEnemy()
    }

    // 检查是否应该生成Boss
    this.checkBossSpawn()

    // 更新UI
    this.updateUI()
  }

  // 渲染游戏画面
  render() {
    // 清空画布
    this.ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT)

    // 绘制星空背景
    this.drawStarfield()

    // 绘制玩家
    this.player.render(this.ctx)

    // 绘制子弹
    for (const bullet of this.bullets) {
      bullet.render(this.ctx)
    }

    // 绘制Boss子弹
    for (const bullet of this.bossBullets) {
      bullet.render(this.ctx)
    }

    // 绘制敌机
    for (const enemy of this.enemies) {
      enemy.render(this.ctx)
    }

    // 绘制Boss
    if (this.boss) {
      this.boss.render(this.ctx)
    }

    // 绘制爆炸效果
    for (const explosion of this.explosions) {
      explosion.render(this.ctx)
    }

    // 绘制道具
    for (const powerUp of this.powerUps) {
      powerUp.render(this.ctx)
    }

    // 绘制拾取特效
    this.renderPickupEffects()

    // 绘制特殊视觉效果
    this.renderSpecialEffects()

    // 绘制状态效果
    this.renderStatusEffects()

    // 如果玩家有护盾，绘制护盾效果
    if (this.player.hasShield) {
      this.drawShield()
    }
  }

  // 绘制道具拾取特效
  renderPickupEffects() {
    for (const effect of this.pickupEffects) {
      this.ctx.beginPath()
      this.ctx.arc(effect.x, effect.y, effect.radius, 0, Math.PI * 2)

      // 根据道具类型设置不同的颜色
      let color
      switch (effect.type) {
        case 'weapon':
          color = `rgba(255, 100, 0, ${effect.opacity})`
          break
        case 'shield':
          color = `rgba(0, 170, 255, ${effect.opacity})`
          break
        case 'life':
          color = `rgba(255, 0, 85, ${effect.opacity})`
          break
        case 'bomb':
          color = `rgba(255, 50, 0, ${effect.opacity})`
          break
        case 'slow':
          color = `rgba(136, 136, 255, ${effect.opacity})`
          break
        default:
          color = `rgba(255, 255, 255, ${effect.opacity})`
      }

      this.ctx.strokeStyle = color
      this.ctx.lineWidth = 3
      this.ctx.stroke()
    }
  }

  // 绘制特殊视觉效果
  renderSpecialEffects() {
    for (const effect of this.specialEffects) {
      effect.render(this.ctx)
    }
  }

  // 绘制星空背景
  drawStarfield() {
    // 这里可以实现星空背景效果
    // 简单起见，我们只绘制一些随机的点
    this.ctx.fillStyle = 'white'
    for (let i = 0; i < 100; i++) {
      const x = Math.random() * CANVAS_WIDTH
      const y = (Date.now() / 50 + i * 10) % CANVAS_HEIGHT
      const size = Math.random() * 2 + 1
      this.ctx.fillRect(x, y, size, size)
    }
  }

  // 绘制护盾效果
  drawShield() {
    // 脉动效果
    const time = Date.now() / 200
    const scale = 0.8 + Math.sin(time) * 0.05

    this.ctx.beginPath()
    this.ctx.arc(
      this.player.x + this.player.width / 2,
      this.player.y + this.player.height / 2,
      this.player.width * scale,
      0,
      Math.PI * 2
    )
    this.ctx.strokeStyle = 'rgba(0, 170, 255, 0.8)'
    this.ctx.lineWidth = 3
    this.ctx.stroke()

    this.ctx.beginPath()
    this.ctx.arc(
      this.player.x + this.player.width / 2,
      this.player.y + this.player.height / 2,
      this.player.width * scale,
      0,
      Math.PI * 2
    )
    this.ctx.fillStyle = 'rgba(0, 170, 255, 0.2)'
    this.ctx.fill()

    // 添加旋转光点效果
    const numDots = 8
    const radius = this.player.width * scale

    for (let i = 0; i < numDots; i++) {
      const angle = (time / 2 + i * ((Math.PI * 2) / numDots)) % (Math.PI * 2)
      const dotX =
        this.player.x + this.player.width / 2 + Math.cos(angle) * radius
      const dotY =
        this.player.y + this.player.height / 2 + Math.sin(angle) * radius

      this.ctx.beginPath()
      this.ctx.arc(dotX, dotY, 2, 0, Math.PI * 2)
      this.ctx.fillStyle = 'rgba(255, 255, 255, 0.8)'
      this.ctx.fill()
    }
  }

  // 生成敌机
  spawnEnemy() {
    // 随机决定敌机类型
    const random = Math.random()

    let enemy
    if (random < EnemyFactory.TYPE_PROBABILITY.small) {
      enemy = EnemyFactory.createEnemy('small')
    } else if (
      random <
      EnemyFactory.TYPE_PROBABILITY.small + EnemyFactory.TYPE_PROBABILITY.medium
    ) {
      enemy = EnemyFactory.createEnemy('medium')
    } else {
      enemy = EnemyFactory.createEnemy('large')
    }

    // 如果有减速效果，应用减速
    if (this.enemySlowFactor !== 1) {
      enemy.originalSpeed = enemy.speed
      enemy.speed *= this.enemySlowFactor
    }

    this.enemies.push(enemy)
  }

  // 创建爆炸效果
  createExplosion(x, y, enemyType = 'small') {
    this.explosions.push(new Explosion(x, y, enemyType))
  }

  // 更新UI
  updateUI() {
    this.scoreElement.textContent = this.score
    this.livesElement.textContent = this.lives
    this.finalScoreElement.textContent = this.score
    this.updateStatusEffectsUI()
  }

  // 游戏结束
  gameOver() {
    this.running = false
    this.gameOverScreen.style.display = 'flex'
  }

  // 绑定事件处理器
  bindEvents() {
    this.startButton.addEventListener('click', this.init.bind(this))
    this.restartButton.addEventListener('click', this.init.bind(this))

    // 键盘控制
    document.addEventListener('keydown', (e) => {
      if (!this.running) return

      switch (e.key) {
        case 'ArrowLeft':
          this.player.isMovingLeft = true
          break
        case 'ArrowRight':
          this.player.isMovingRight = true
          break
        case 'ArrowUp':
          this.player.isMovingUp = true
          break
        case 'ArrowDown':
          this.player.isMovingDown = true
          break
        case ' ':
          this.player.isShooting = true
          break
      }
    })

    document.addEventListener('keyup', (e) => {
      switch (e.key) {
        case 'ArrowLeft':
          this.player.isMovingLeft = false
          break
        case 'ArrowRight':
          this.player.isMovingRight = false
          break
        case 'ArrowUp':
          this.player.isMovingUp = false
          break
        case 'ArrowDown':
          this.player.isMovingDown = false
          break
        case ' ':
          this.player.isShooting = false
          break
      }
    })
  }

  // 根据武器等级发射子弹
  fireBullets() {
    const weaponLevel = this.player.weaponLevel || 1
    const playerCenterX = this.player.x + this.player.width / 2

    switch (weaponLevel) {
      case 1:
        // 等级1：发射单发子弹
        this.bullets.push(
          new Bullet(playerCenterX - Bullet.WIDTH / 2, this.player.y, 1)
        )
        break
      case 2:
        // 等级2：发射双发子弹
        this.bullets.push(
          new Bullet(playerCenterX - Bullet.WIDTH - 5, this.player.y, 2)
        )
        this.bullets.push(new Bullet(playerCenterX + 5, this.player.y, 2))
        break
      case 3:
        // 等级3：发射三发子弹
        this.bullets.push(
          new Bullet(playerCenterX - Bullet.WIDTH - 10, this.player.y, 3)
        )
        this.bullets.push(
          new Bullet(playerCenterX - Bullet.WIDTH / 2, this.player.y - 5, 3)
        )
        this.bullets.push(new Bullet(playerCenterX + 10, this.player.y, 3))
        break
    }
  }

  // 随机掉落道具
  dropPowerUp(enemy) {
    // 根据掉落概率决定是否掉落道具
    if (Math.random() < POWERUP_DROP_CHANCE) {
      const powerUp = PowerUpFactory.createPowerUp(
        enemy.x + enemy.width / 2 - 15,
        enemy.y + enemy.height / 2 - 15
      )
      this.powerUps.push(powerUp)
    }
  }

  // 添加道具拾取特效
  addPickupEffect(effect) {
    this.pickupEffects.push(effect)
  }

  // 添加特殊视觉效果
  addSpecialEffect(effect) {
    this.specialEffects.push(effect)
  }

  // 添加状态效果
  addStatusEffect(effect) {
    // 检查是否已存在同类型的状态效果
    const existingEffectIndex = this.statusEffects.findIndex(
      (e) => e.type === effect.type
    )

    if (existingEffectIndex !== -1) {
      // 如果存在，则更新
      this.statusEffects[existingEffectIndex] = {
        ...this.statusEffects[existingEffectIndex],
        ...effect,
      }
    } else {
      // 如果不存在，则添加
      this.statusEffects.push(effect)
    }

    // 更新UI
    this.updateStatusEffectsUI()
  }

  // 更新状态效果
  updateStatusEffect(type, updates) {
    const effectIndex = this.statusEffects.findIndex((e) => e.type === type)

    if (effectIndex !== -1) {
      this.statusEffects[effectIndex] = {
        ...this.statusEffects[effectIndex],
        ...updates,
      }

      // 更新UI
      this.updateStatusEffectsUI()
    }
  }

  // 移除状态效果
  removeStatusEffect(type) {
    this.statusEffects = this.statusEffects.filter((e) => e.type !== type)

    // 更新UI
    this.updateStatusEffectsUI()
  }

  // 更新状态效果
  updateStatusEffects() {
    const now = Date.now()

    // 检查状态效果是否过期
    for (let i = this.statusEffects.length - 1; i >= 0; i--) {
      const effect = this.statusEffects[i]
      const elapsedTime = now - effect.startTime

      if (elapsedTime >= effect.duration) {
        // 如果过期，则移除
        this.statusEffects.splice(i, 1)
      }
    }

    // 更新UI
    this.updateStatusEffectsUI()
  }

  // 更新状态效果UI
  updateStatusEffectsUI() {
    if (!this.statusEffectsElement) return

    // 清空状态效果UI
    this.statusEffectsElement.innerHTML = ''

    // 添加状态效果图标
    for (const effect of this.statusEffects) {
      const effectElement = document.createElement('div')
      effectElement.className = 'status-effect'

      // 设置图标
      switch (effect.type) {
        case 'weapon':
          effectElement.innerHTML = `<span class="icon">🔫</span><span class="level">${effect.level}</span>`
          break
        case 'shield':
          effectElement.innerHTML = '<span class="icon">🛡️</span>'
          break
        case 'slow':
          effectElement.innerHTML = '<span class="icon">⏱️</span>'
          break
      }

      // 计算剩余时间
      const now = Date.now()
      const elapsedTime = now - effect.startTime
      const remainingTime = Math.max(0, effect.duration - elapsedTime)
      const remainingSeconds = Math.ceil(remainingTime / 1000)

      // 添加剩余时间
      const timeElement = document.createElement('span')
      timeElement.className = 'time'
      timeElement.textContent = `${remainingSeconds}s`
      effectElement.appendChild(timeElement)

      // 添加到UI
      this.statusEffectsElement.appendChild(effectElement)
    }
  }

  // 渲染状态效果
  renderStatusEffects() {
    // 如果有减速效果，绘制全局减速效果
    if (this.statusEffects.some((e) => e.type === 'slow')) {
      // 使用渐变色而不是纯色，增强视觉效果
      const gradient = this.ctx.createRadialGradient(
        CANVAS_WIDTH / 2,
        CANVAS_HEIGHT / 2,
        0,
        CANVAS_WIDTH / 2,
        CANVAS_HEIGHT / 2,
        CANVAS_WIDTH
      )
      gradient.addColorStop(0, 'rgba(0, 0, 255, 0.05)')
      gradient.addColorStop(1, 'rgba(0, 0, 255, 0.15)')

      this.ctx.fillStyle = gradient
      this.ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT)

      // 添加时间减缓的视觉提示 - 边缘蓝色光晕
      this.ctx.strokeStyle = 'rgba(0, 0, 255, 0.3)'
      this.ctx.lineWidth = 10
      this.ctx.strokeRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT)
    }

    // 如果有武器升级效果，添加武器升级的视觉提示
    const weaponEffect = this.statusEffects.find((e) => e.type === 'weapon')
    if (weaponEffect) {
      const level = weaponEffect.level
      const colors = [
        '',
        'rgba(255, 255, 0, 0.1)',
        'rgba(255, 165, 0, 0.1)',
        'rgba(255, 0, 0, 0.1)',
      ]

      if (level > 1) {
        // 在玩家周围绘制光环
        this.ctx.beginPath()
        this.ctx.arc(
          this.player.x + this.player.width / 2,
          this.player.y + this.player.height / 2,
          this.player.width * 1.5,
          0,
          Math.PI * 2
        )
        this.ctx.fillStyle = colors[level]
        this.ctx.fill()
      }
    }
  }

  // 显示提示信息
  showMessage(text, duration = 2000) {
    if (!this.messageElement) return

    // 显示提示信息
    this.messageElement.textContent = text
    this.messageElement.style.display = 'block'
    this.messageElement.style.opacity = '1'

    // 设置定时器，在指定时间后隐藏提示信息
    setTimeout(() => {
      this.messageElement.style.opacity = '0'
      setTimeout(() => {
        this.messageElement.style.display = 'none'
      }, 500)
    }, duration)
  }

  // 更新敌机
  updateEnemies(timestamp) {
    // 更新敌机位置
    for (let i = this.enemies.length - 1; i >= 0; i--) {
      this.enemies[i].update()

      // 移除超出屏幕的敌机
      if (this.enemies[i].isOutOfScreen()) {
        this.enemies.splice(i, 1)
        continue
      }

      // 检测敌机与玩家的碰撞
      if (checkCollision(this.enemies[i], this.player)) {
        // 如果玩家有护盾，则不受伤害
        if (this.player.hasShield) {
          // 创建爆炸效果
          this.createExplosion(
            this.enemies[i].x + this.enemies[i].width / 2,
            this.enemies[i].y + this.enemies[i].height / 2,
            this.enemies[i].type
          )

          // 播放爆炸音效
          playSound('explosion')

          // 增加分数
          this.score += this.enemies[i].score
          this.updateUI()

          // 移除敌机
          this.enemies.splice(i, 1)
        } else {
          // 创建爆炸效果
          this.createExplosion(
            this.enemies[i].x + this.enemies[i].width / 2,
            this.enemies[i].y + this.enemies[i].height / 2,
            this.enemies[i].type
          )

          // 播放爆炸音效
          playSound('explosion')

          this.enemies.splice(i, 1)
          this.lives--
          this.updateUI()

          if (this.lives <= 0) {
            this.gameOver()
            return
          }
        }
        continue
      }

      // 检测敌机与子弹的碰撞
      for (let j = this.bullets.length - 1; j >= 0; j--) {
        if (checkCollision(this.enemies[i], this.bullets[j])) {
          // 减少敌机生命值
          this.enemies[i].takeDamage(1)

          // 移除子弹
          this.bullets.splice(j, 1)

          // 如果敌机生命值为0，则销毁敌机
          if (this.enemies[i].health <= 0) {
            // 创建爆炸效果
            this.createExplosion(
              this.enemies[i].x + this.enemies[i].width / 2,
              this.enemies[i].y + this.enemies[i].height / 2,
              this.enemies[i].type
            )

            // 播放爆炸音效
            playSound('explosion')

            // 增加分数
            this.score += this.enemies[i].score
            this.updateUI()

            // 随机掉落道具
            this.dropPowerUp(this.enemies[i])

            // 移除敌机
            this.enemies.splice(i, 1)
          }
          break
        }
      }
    }
  }

  // 更新Boss
  updateBoss(timestamp) {
    if (this.boss) {
      // 更新Boss
      const result = this.boss.update(timestamp)

      // 处理Boss返回的结果
      if (result) {
        // 如果返回的是子弹数组
        if (Array.isArray(result)) {
          // 检查子弹类型
          for (const bulletData of result) {
            // 如果是普通子弹
            if (!bulletData.type || bulletData.type === 'normal') {
              const bullet = new Bullet(
                bulletData.x,
                bulletData.y,
                bulletData.speedX,
                bulletData.speedY,
                'enemy',
                bulletData.damage || 1
              )
              this.bossBullets.push(bullet)
            }
            // 如果是激光子弹
            else if (bulletData.type === 'laser') {
              const bullet = new Bullet(
                bulletData.x,
                bulletData.y,
                bulletData.speedX,
                bulletData.speedY,
                'laser',
                bulletData.damage || 2
              )
              // 设置激光子弹的特殊属性
              bullet.width = bulletData.width || 20
              bullet.height = bulletData.height || 20
              bullet.isLaser = true
              this.bossBullets.push(bullet)
            }
            // 如果是召唤小敌机
            else if (bulletData.type === 'summoned') {
              const enemy = {
                x: bulletData.x,
                y: bulletData.y,
                width: 30,
                height: 30,
                speed: bulletData.speed || 2,
                health: bulletData.health || 2,
                score: 100,
                type: 'small',
                image: new Image(),
              }
              enemy.image.src = 'images/enemy_small.png'
              enemy.update = function () {
                this.y += this.speed
              }
              enemy.render = function (ctx) {
                ctx.drawImage(
                  this.image,
                  this.x,
                  this.y,
                  this.width,
                  this.height
                )
              }
              enemy.isOutOfScreen = function () {
                return this.y > CANVAS_HEIGHT
              }
              enemy.takeDamage = function (amount) {
                this.health -= amount
              }
              this.enemies.push(enemy)
            }
          }

          // 播放Boss发射子弹的音效
          if (result.length > 0) {
            // 根据子弹类型播放不同音效
            if (result[0].type === 'laser') {
              playSound('boss_laser')
            } else if (result[0].type === 'summoned') {
              playSound('boss_summon')
            } else {
              playSound('boss_fire')
            }
          }
        }
      }

      // 检查Boss是否离开屏幕
      if (this.boss.isOutOfScreen()) {
        this.boss = null
        this.bossActive = false
      }
    }

    // 更新Boss子弹
    this.updateBossBullets()
  }

  // 更新Boss子弹
  updateBossBullets() {
    for (let i = this.bossBullets.length - 1; i >= 0; i--) {
      const bullet = this.bossBullets[i]
      bullet.update()

      // 如果子弹离开屏幕，移除子弹
      if (bullet.isOutOfScreen()) {
        this.bossBullets.splice(i, 1)
      }
    }
  }

  // 检查是否应该生成Boss
  checkBossSpawn() {
    if (
      !this.bossActive &&
      BossFactory.shouldSpawnBoss(this.score, this.lastBossSpawnScore)
    ) {
      this.spawnBoss()
    }
  }

  // 生成Boss
  spawnBoss() {
    // 获取Boss类型
    const bossType = BossFactory.getBossTypeByScore(this.score)

    // 创建Boss
    this.boss = BossFactory.createBoss(bossType)
    this.bossActive = true

    // 记录生成Boss的分数
    this.lastBossSpawnScore = this.score

    // 清除所有普通敌机
    this.enemies = []

    // 显示Boss出场消息
    this.showMessage('Boss来袭！', 3000)

    // 播放Boss出场音效
    playSound('boss_appear')
  }

  // 创建Boss爆炸效果
  createBossExplosion() {
    // 在Boss位置创建多个爆炸效果
    if (this.boss) {
      const centerX = this.boss.x + this.boss.width / 2
      const centerY = this.boss.y + this.boss.height / 2

      // 创建一个大型爆炸
      this.createExplosion(centerX, centerY, 'large')

      // 创建多个小型爆炸
      for (let i = 0; i < 8; i++) {
        const offsetX = (Math.random() - 0.5) * this.boss.width
        const offsetY = (Math.random() - 0.5) * this.boss.height

        this.createExplosion(
          centerX + offsetX,
          centerY + offsetY,
          Math.random() < 0.5 ? 'small' : 'medium'
        )
      }
    }
  }

  // Boss掉落多个道具
  dropBossPowerUps() {
    if (this.boss) {
      const centerX = this.boss.x + this.boss.width / 2
      const centerY = this.boss.y + this.boss.height / 2

      // 掉落多种道具
      const powerUpTypes = ['weapon', 'shield', 'life', 'bomb', 'slow']

      for (const type of powerUpTypes) {
        const offsetX = (Math.random() - 0.5) * this.boss.width * 0.8
        const offsetY = (Math.random() - 0.5) * this.boss.height * 0.8

        const powerUp = PowerUpFactory.createPowerUp(
          centerX + offsetX,
          centerY + offsetY,
          type
        )
        this.powerUps.push(powerUp)
      }
    }
  }

  // 更新爆炸效果
  updateExplosions() {
    // 更新爆炸效果
    for (let i = this.explosions.length - 1; i >= 0; i--) {
      this.explosions[i].update()
      if (this.explosions[i].isFinished()) {
        this.explosions.splice(i, 1)
      }
    }
  }

  // 更新道具
  updatePowerUps() {
    // 更新道具位置
    for (let i = this.powerUps.length - 1; i >= 0; i--) {
      this.powerUps[i].update()

      // 移除超出屏幕的道具
      if (this.powerUps[i].isOutOfScreen()) {
        this.powerUps.splice(i, 1)
      }
    }
  }

  // 更新拾取特效
  updatePickupEffects() {
    // 更新道具拾取特效
    for (let i = this.pickupEffects.length - 1; i >= 0; i--) {
      const effect = this.pickupEffects[i]
      effect.radius += effect.growSpeed
      effect.opacity -= 0.05

      if (effect.opacity <= 0 || effect.radius >= effect.maxRadius) {
        this.pickupEffects.splice(i, 1)
      }
    }
  }

  // 更新特殊视觉效果
  updateSpecialEffects() {
    // 更新特殊视觉效果
    for (let i = this.specialEffects.length - 1; i >= 0; i--) {
      const effect = this.specialEffects[i]
      const isActive = effect.update()

      if (!isActive) {
        this.specialEffects.splice(i, 1)
      }
    }
  }

  // 检测碰撞
  checkCollisions() {
    // 检测玩家子弹与敌机的碰撞
    for (let i = this.bullets.length - 1; i >= 0; i--) {
      const bullet = this.bullets[i]

      // 检测子弹与敌机的碰撞
      for (let j = this.enemies.length - 1; j >= 0; j--) {
        const enemy = this.enemies[j]

        if (checkCollision(bullet, enemy)) {
          // 敌机受到伤害
          enemy.takeDamage(bullet.damage)

          // 移除子弹
          this.bullets.splice(i, 1)

          // 如果敌机被击毁
          if (enemy.health <= 0) {
            // 创建爆炸效果
            this.createExplosion(
              enemy.x + enemy.width / 2,
              enemy.y + enemy.height / 2,
              enemy.type
            )

            // 播放爆炸音效
            playSound('explosion')

            // 增加分数
            this.score += enemy.score

            // 随机掉落道具
            this.dropPowerUp(enemy)

            // 移除敌机
            this.enemies.splice(j, 1)
          }

          break
        }
      }

      // 检测子弹与Boss的碰撞
      if (this.boss && bullet && checkCollision(bullet, this.boss)) {
        // Boss受到伤害
        const isBossDefeated = this.boss.takeDamage(bullet.damage)

        // 移除子弹
        this.bullets.splice(i, 1)

        // 如果Boss被击败
        if (isBossDefeated) {
          // 增加分数
          this.score += this.boss.score

          // 创建大型爆炸效果
          this.createBossExplosion()

          // 掉落多个道具
          this.dropBossPowerUps()

          // 清除Boss
          this.boss = null
          this.bossActive = false

          // 显示Boss击败消息
          this.showMessage('Boss击败！', 3000)

          // 播放Boss击败音效
          playSound('boss_defeated')
        }
      }
    }

    // 检测敌机与玩家的碰撞
    for (let i = this.enemies.length - 1; i >= 0; i--) {
      const enemy = this.enemies[i]

      if (checkCollision(enemy, this.player)) {
        // 如果玩家有护盾，不受伤害
        if (this.player.hasShield) {
          // 创建爆炸效果
          this.createExplosion(
            enemy.x + enemy.width / 2,
            enemy.y + enemy.height / 2,
            enemy.type
          )

          // 移除敌机
          this.enemies.splice(i, 1)

          // 播放护盾碰撞音效
          playSound('shield_hit')
        } else {
          // 玩家失去一条生命
          this.lives--

          // 创建爆炸效果
          this.createExplosion(
            enemy.x + enemy.width / 2,
            enemy.y + enemy.height / 2,
            enemy.type
          )

          // 移除敌机
          this.enemies.splice(i, 1)

          // 播放玩家受伤音效
          playSound('player_hit')

          // 如果生命值为0，游戏结束
          if (this.lives <= 0) {
            this.gameOver()
          }
        }
      }
    }

    // 检测Boss子弹与玩家的碰撞
    for (let i = this.bossBullets.length - 1; i >= 0; i--) {
      const bullet = this.bossBullets[i]

      if (checkCollision(bullet, this.player)) {
        // 如果玩家有护盾，不受伤害
        if (this.player.hasShield) {
          // 移除子弹
          this.bossBullets.splice(i, 1)

          // 播放护盾碰撞音效
          playSound('shield_hit')
        } else {
          // 玩家失去一条生命
          this.lives--

          // 移除子弹
          this.bossBullets.splice(i, 1)

          // 播放玩家受伤音效
          playSound('player_hit')

          // 如果生命值为0，游戏结束
          if (this.lives <= 0) {
            this.gameOver()
          }
        }
      }
    }

    // 检测道具与玩家的碰撞
    for (let i = this.powerUps.length - 1; i >= 0; i--) {
      const powerUp = this.powerUps[i]

      if (checkCollision(powerUp, this.player)) {
        // 应用道具效果
        powerUp.apply(this.player, this)

        // 显示拾取特效
        powerUp.showPickupEffect(this)

        // 移除道具
        this.powerUps.splice(i, 1)

        // 播放道具拾取音效
        playSound('powerup')
      }
    }
  }
}
